<?php

// | 腾讯企业邮箱单点登录开发

Class Exmail{
	
	protected $corpid;
    protected $secret;
    protected $accessToken;
	
	function __construct(){
		$this->corpid			= "";//企业id
		$this->secret			= "";//应用的secret(凭证密钥)
		$this->cache			= "cache";//缓存文件
		$this->accessToken		= $this->getAccessToken();
	}

	/***
	 * 获取登录URL
	 * @userid 邮箱地址
	 * @return json
	 **/
	public function loginUrl($userid){
		$arr = json_decode( $this->getLogin($userid), true );
		return $arr['login_url'];
	}
	
	/***
	 * 获取 access_token
	 * token的有效时间为2小时，使用cache存储在当前文件通马路的cache设置的文件中
	 * @return
	 **/
	private function getAccessToken(){
		$file = $this->cache;
		if(file_exists($file)){
			$data = json_decode(file_get_contents($file),true);
			if(filemtime($file)+$data['expires_in']>=time()){
				return $data['access_token'];
			}
		}
		$url = "https://api.exmail.qq.com/cgi-bin/gettoken?corpid=".$this->corpid."&corpsecret=".$this->secret;
		$res = $this->http($url);
		$json = json_decode($res,true);
		$fp	=	fopen($file,"w");//access_token 缓存文件
		flock	($fp, LOCK_EX);
		fwrite	($fp, $res);
		flock	($fp, LOCK_UN);
		fclose	($fp);
		return $json['access_token'];
	}
	
	/***
	 * 获取登录URL
	 * @userid 邮箱地址
	 * @return json
	 **/
	private function getLogin($userid){
		$url = "https://api.exmail.qq.com/cgi-bin/service/get_login_url?access_token=".$this->accessToken."&userid=".$userid;
		$res = $this->http($url);
		return $res;
	}
	
	/***
	 * POST或GET请求
	 * @url 请求url
	 * @data POST数据
	 * @return
	 **/
	private function http($url, $data = ""){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		if(!empty($data)){	//判断是否为POST请求
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}
	
}